import { defineComponent, h, ref, unref } from "vue";
import { Modal } from "ant-design-vue";
import { omit } from "lodash-es";
import SchemaForm from "@/schema/schema-form";

export default defineComponent({
  components: {
    Modal,
    SchemaForm,
  },
  props: {
    modalProps: {
      type: Object,
      default: () => ({}),
    },
    formProps: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ["vanish"],
  setup(props, context) {
    const { modalProps, formProps } = unref(props);
    const { emit } = context;
    const contentRef = ref();
    const visibleModel = ref<boolean>(true);
    const handleOk = () => {
      contentRef.value?.formRef.validate().then(async (value) => {
        await modalProps?.onFinish(value);
        visibleModel.value = false;
      });
    };

    const handleCancel = () => {
      modalProps.onCancel && modalProps.onCancel();
      emit("vanish");
    };

    return () => (
      <Modal
        v-model:visible={visibleModel.value}
        {...omit(modalProps, ["onFinish", "onCancel", "onOk"])}
        onOk={handleOk}
        onCancel={handleCancel}
        maskClosable={false}
      >
        {h(SchemaForm, {
          ref: contentRef,
          ...formProps,
        })}
      </Modal>
    );
  },
});
